package com.open.party.cloud.view.examine

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.core.content.ContextCompat
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import com.alibaba.fastjson.JSON
import com.jiangyy.easydialog.CommonDialog
import com.open.party.cloud.R
import com.open.party.cloud.model.ExamineSubmitResultVo
import com.open.party.cloud.model.ExamineSubmitVo
import com.open.party.cloud.model.PeiXunKaoShiInfoBean
import com.open.party.cloud.model.PeiXunKaoShiInfoBean.SubjectListBean
import com.open.party.cloud.viewModel.BizViewModel
import com.open.party.cloud.viewModel.ExamineViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.switchTabView.style1.UIUtil
import kotlinx.android.synthetic.main.dygbjy_pei_xun_kao_shi_detail.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class ExamineDoingActivity : AppEventBusTitleBaseActivity() {
    private var viewModel: ExamineViewModel? = null
    private var viewModelTemp: BizViewModel? = null
    private var examinationId = ""

    override fun getLayoutResId(): Int = R.layout.dygbjy_pei_xun_kao_shi_detail

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        examinationId = intent.getStringExtra("examinationId") as String
        viewModelTemp = BizViewModel()
        viewModel = ExamineViewModel()

        viewModelTemp!!.getPeiXunKaoShiDetail(examinationId)

        submitBtn.setOnClickListener {
            submitExamineAnswer(false)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<PeiXunKaoShiInfoBean>) {
        if (result.eventType != "getPeiXunKaoShiDetail") {
            return
        }
        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    showData(result.data)
                    nestedScrollView.visibility = View.VISIBLE
                } else {
                    XUtils.toast().show("数据异常")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
                XUtils.toast().show("Token过期，请重新登录")
            }
            else -> {
                XUtils.toast().show(result.msg)
                finish()
            }
        }
    }

    private fun submitExamineAnswer(autoSubmit: Boolean) {
        val saveVO = ExamineSubmitVo()
        saveVO.eid = examinationId
        saveVO.alist = ArrayList()

        if (currSubjectList != null) {
            for (index in currSubjectList!!.indices) {


                if (currSubjectList!![index].submitResultVo != null
                    && currSubjectList!![index].submitResultVo.optionNumArr != null
                    && currSubjectList!![index].submitResultVo.optionNumArr.isNotEmpty()
                ) {
                    var optionNum = "" // 取出答案内容
                    for (num in currSubjectList!![index].submitResultVo.optionNumArr.indices) {

                        if (XUtils.string().isNotEmpty(currSubjectList!![index].submitResultVo.optionNumArr[num])) {

                            optionNum = if (XUtils.string().isEmpty(optionNum)) {
                                XUtils.string().getNotNullValue(currSubjectList!![index].submitResultVo.optionNumArr[num])
                            } else {
                                optionNum + "," + currSubjectList!![index].submitResultVo.optionNumArr[num]
                            }
                        }
                    }

                    currSubjectList!![index].submitResultVo.optionNum = optionNum

                    // 构建新答案
                    saveVO.alist.add(currSubjectList!![index].submitResultVo)
                }
            }
        }

        if (!autoSubmit) {
            // 手动提交时，判断是否做完
            var hasDoneNum = 0
            for (answer in saveVO.alist) {
                if (XUtils.string().isNotEmpty(answer.optionNum)) {
                    hasDoneNum++
                }
            }

            CommonDialog.Builder(this)
                .setCancelable(false)
                .setTitle("交卷提示")
                .setMessage("共有题目：${saveVO.alist.size} 题\n已做题目：${hasDoneNum} 题\n\n确定要交卷吗？")
                .setPositiveButton("确定") {
//                    Log.e("RxRetrofit", "vo: \n" + JSON.toJSONString(saveVO))
                    showLoadingDialog("正在提交")
                    viewModel!!.submitExamineAnswer(saveVO)

                    if (timer != null) {
                        timer!!.cancel()
                    }
                }.setNegativeButton("取消") {
                }.show()
        } else {
//            Log.e("RxRetrofit", "vo: \n" + JSON.toJSONString(saveVO))
            showLoadingDialog("正在提交")
            viewModel!!.submitExamineAnswer(saveVO)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusSubmitCallback(result: ResultInfo<String>) {
        if (result.eventType != "submitExamineAnswer") {
            return
        }
        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    XUtils.toast().show("考试成功")
                    finish()
                } else {
                    XUtils.toast().show("")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    private var currSubjectList: ArrayList<SubjectListBean>? = null

    @SuppressLint("SetTextI18n")
    private fun showData(data: PeiXunKaoShiInfoBean) {
        setViewTitle("考试试题", "${data.lengthOfExamination}分钟", null)

        if (data.lengthOfExamination > 0) {
            initTimer(data.lengthOfExamination)
        }

        // 内容部分
        titleTv.text = XUtils.string().getNotNullValue(data.name)
        contentTv.text = XUtils.string().getNotNullValue(data.briefIntroduction)

        if (data.subjectList != null && data.subjectList.size > 0) {
            currSubjectList = data.subjectList

            for (index in data.subjectList.indices) {

                var qTitleTv: TextView? = null

                val item = data.subjectList[index]

                // 创建做题答案对象
                data.subjectList[index].submitResultVo = ExamineSubmitResultVo(item.id, item.sort, item.type.code)

                when (item.type.code) {
                    "SINGLE" -> {
                        val view01 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_01, null)
                        qTitleTv = view01.findViewById(R.id.qTitleTv)

                        val radioGroup: RadioGroup = view01.findViewById(R.id.radioGroup)

                        data.subjectList[index].submitResultVo.optionNumArr = arrayOfNulls<String>(item.saList.size)
                        for (subIndex in item.saList.indices) {
                            // 选项
                            val subItem = item.saList[subIndex]

                            val rb = RadioButton(this)
                            rb.text = subItem.optionNum + "、" + subItem.option
                            rb.setTextColor(ContextCompat.getColor(this@ExamineDoingActivity, R.color.page_content))
                            rb.paint.textSize = UIUtil.sp2px(this, 13f).toFloat()

                            rb.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
//                                val optionNum_Old = if (XUtils.string().isEmpty(data.subjectList[index].submitResultVo.optionNum)) {
//                                    ""
//                                } else {
//                                    data.subjectList[index].submitResultVo.optionNum
//                                }

                                if (isChecked) {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old + "," + subItem.optionNum

                                    data.subjectList[index].submitResultVo.optionNumArr[subIndex] = subItem.optionNum

                                } else {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old.replace("," + subItem.optionNum, "")

                                    data.subjectList[index].submitResultVo.optionNumArr[subIndex] = ""
                                }
                            })

                            radioGroup.addView(rb, subIndex)
                        }

                        itemsView.addView(view01, index)
                    }

                    "MANY" -> {
                        val view02 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_02, null)
                        qTitleTv = view02.findViewById(R.id.qTitleTv)

                        val checkBoxView: LinearLayout = view02.findViewById(R.id.checkBoxView)

                        data.subjectList[index].submitResultVo.optionNumArr = arrayOfNulls<String>(item.saList.size)
                        for (subIndex in item.saList.indices) {
                            // 选项
                            val subItem = item.saList[subIndex]

                            val cb = CheckBox(this)
                            cb.text = subItem.optionNum + "、" + subItem.option
                            cb.setTextColor(ContextCompat.getColor(this@ExamineDoingActivity, R.color.page_content))
                            cb.paint.textSize = UIUtil.sp2px(this, 13f).toFloat()

                            cb.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
//                                val optionNum_Old = if (XUtils.string().isEmpty(data.subjectList[index].submitResultVo.optionNum)) {
//                                    ""
//                                } else {
//                                    data.subjectList[index].submitResultVo.optionNum
//                                }

                                if (isChecked) {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old + "," + subItem.optionNum

                                    data.subjectList[index].submitResultVo.optionNumArr[subIndex] = subItem.optionNum
                                } else {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old.replace("," + subItem.optionNum, "")

                                    data.subjectList[index].submitResultVo.optionNumArr[subIndex] = ""
                                }
                            })

                            checkBoxView.addView(cb, subIndex)
                        }

                        itemsView.addView(view02, index)
                    }
                    "CONTENT" -> {
                        val view03 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_03, null)
                        qTitleTv = view03.findViewById(R.id.qTitleTv)

                        data.subjectList[index].submitResultVo.optionNumArr = arrayOfNulls<String>(1)

                        val contentEt: EditText = view03.findViewById(R.id.contentEt)
                        contentEt.addTextChangedListener(object : TextWatcher {
                            override fun afterTextChanged(s: Editable?) {
                            }

                            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                            }

                            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                                data.subjectList[index].submitResultVo.optionNumArr[0] = s.toString()
                            }
                        })

                        itemsView.addView(view03, index)
                    }

                    "TK" -> {
                        val view04 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_04, null)
                        qTitleTv = view04.findViewById(R.id.qTitleTv)

                        val tkContentView: LinearLayout = view04.findViewById(R.id.tkContentView)

                        data.subjectList[index].submitResultVo.optionNumArr = arrayOfNulls<String>(item.saList.size)
                        for (subIndex in item.saList.indices) {
                            // 选项
                            val subItem = item.saList[subIndex]

                            val view04SubView = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_04_content, null)
                            val tipTv: TextView = view04SubView.findViewById(R.id.tipTv)
                            tipTv.text = "空格${subIndex + 1}"


                            val contentEt: EditText = view04SubView.findViewById(R.id.contentEt)
                            contentEt.addTextChangedListener(object : TextWatcher {
                                override fun afterTextChanged(s: Editable?) {
                                }

                                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                                }

                                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                                    data.subjectList[index].submitResultVo.optionNumArr[subIndex] = s.toString()
                                }
                            })

                            tkContentView.addView(view04SubView, subIndex)
                        }

                        itemsView.addView(view04, index)
                    }

                    "JUDGE" -> {
                        val view05 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_05, null)
                        qTitleTv = view05.findViewById(R.id.qTitleTv)

                        val radioGroup: RadioGroup = view05.findViewById(R.id.radioGroup)

                        data.subjectList[index].submitResultVo.optionNumArr = arrayOfNulls<String>(item.saList.size)
                        for (subIndex in item.saList.indices) {
                            // 选项
                            val subItem = item.saList[subIndex]

                            val rb = RadioButton(this)
                            rb.text = subItem.optionNum + "、" + subItem.option
                            rb.setTextColor(ContextCompat.getColor(this@ExamineDoingActivity, R.color.page_content))
                            rb.paint.textSize = UIUtil.sp2px(this, 13f).toFloat()

                            rb.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
//                                val optionNum_Old = if (XUtils.string().isEmpty(data.subjectList[index].submitResultVo.optionNum)) {
//                                    ""
//                                } else {
//                                    data.subjectList[index].submitResultVo.optionNum
//                                }

//                                if (isChecked) {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old + "," + subItem.optionNum
//                                } else {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old.replace("," + subItem.optionNum, "")
//                                }

                                if (isChecked) {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old + "," + subItem.optionNum

                                    data.subjectList[index].submitResultVo.optionNumArr[subIndex] = subItem.optionNum
                                } else {
//                                    data.subjectList[index].submitResultVo.optionNum = optionNum_Old.replace("," + subItem.optionNum, "")

                                    data.subjectList[index].submitResultVo.optionNumArr[subIndex] = ""
                                }
                            })

                            radioGroup.addView(rb, subIndex)
                        }

                        itemsView.addView(view05, index)
                    }
                }

                if (qTitleTv != null) {
                    // 标题
                    qTitleTv.text = "${index + 1}、${XUtils.string().getNotNullValue(item.titleDescription)} (${item.score}分)"
                }
            }
        }
    }

    // 剩余时间
    private fun refreshTime(tipStr: String) {
        titleBarView.setRight1Txt(tipStr, null)
    }

    private var timer: CountDownTimer? = null

    private fun initTimer(lengthOfExamination: Int) {

        timer = object : CountDownTimer((lengthOfExamination * 60 * 1000).toLong(), 1000) {

            override fun onTick(millisUntilFinished: Long) {
                val min: Long = millisUntilFinished / (60 * 1000)
                val sec: Long = (millisUntilFinished - min * 60 * 1000) / 1000
                val tipStr = if (min != 0L) {
                    "${min}分${sec}秒"
                } else {
                    "${sec}秒"
                }

                refreshTime(tipStr)
            }

            override fun onFinish() {
                titleBarView.setRight1Txt("考试结束", null)
                submitExamineAnswer(true)
            }
        }
        timer!!.start()
    }
}